var ws;
var address = "ws://localhost:2222/example/ssh";
//var address = "ws://10.0.1.3:2222/example/ssh";
var cmd;
myservers = function(){
    var current = {}, availableServers=[], servers=[];
    if(localStorage.servers){
        servers = $.evalJSON(localStorage.servers)
    }

    init_servers = function(){
        $.each(servers, function(index, server){
            availableServers.push({"label":server.ip, "value": server.ip, "name":server.name, "password":server.password})
        })
    }

    clean = function(){
        $("#name").val("")
        $("#password").val("")
    }

    existed = function(ip){
        if(!ip) return false
        exist = false
        $.each(servers, function(index, server){
            if(ip == server.ip){
                exist = true
            }
        })
        return exist
    }

    register = function(ip, name, pwd, width, height){
        if(ip){
            if(!existed(ip)){
                servers.push({
                    "ip":ip,
                    "name":name,
                    "password":pwd
                })

                localStorage.servers =$.toJSON(servers)
            }
            current.ip = ip
            current.name = name
            current.pwd = pwd 
        }
    }

    init_servers()
    return {
        "reg": register, 
        "current":current,
        "availableServers":availableServers
        }
}()


$(function () {
    startbtn();

    $("#ip").autocomplete({
        source: myservers.availableServers,
        appendTo: "header",
        delay:"100",
        autoFocus: true,
        open: function(event, ui){
            $.each($(".ui-autocomplete .ui-corner-all"), function(index, item){
                /*
                $new_item = $(item).width("60%")
                del_btn = $("<span>del</span>").css("float","right").width("30%").css("backgroundColor", "yellow")
                $new_item.after(del_btn)
                */
            })
        },
        focus: function(event, ui){
            //console.info(event)
            //console.info(ui)
        },
        select: function(event, ui) {
            server = ui.item
            $("#name").val(server.name)
            $("#password").val(server.password)
        }
    });
})

function clearbtn() {
    $("input[name='clear']").click(function () {
        $("textarea[name='msg']").val("");
    })
}


function exeResult(data) {
    if(data.result == "CLEAR"){
        $("#main_shower").html("")
    }

}
var new_input = true, is_tab = false;
function parse_result(data){
    var result = data.result, $cmd= $(".cmd_input")
    console.info("result:" + result + " new_input:" + new_input + " cmd:"+$cmd)
    get_cmd_input = function(){
        var command_key = [8,9,13, 37, 38, 39, 40]
        return $("<input class='cmd_input' x-webkit-speech x-webkit-grammar=\"builtin:translate\" autofocus>").keypress(function(arg){
            var keycode = arg.keyCode
            if(command_key.indexOf(keycode) == -1){
                console.info("press : " + keycode)
                ws.send($.toJSON({"keycode":keycode}))
                event.returnValue=false;
            }
        }).keydown(function(arg){
            new_input = false
            var keycode = arg.keyCode
            console.info("down : " + keycode)
            if(command_key.indexOf(keycode) != -1){
                console.info("down : " + keycode)
                switch(keycode){
                    case 9:
                        is_tab = true
                        event.returnValue=false;
                        break;
                    case 13:
                        new_input = true
                        console.info("enter command")
                        break;
                }
                ws.send($.toJSON({"keycode":keycode}))
            }
        })
    }
    if (new_input){
        console.info("create new Input")
        var value = $cmd.val() ||  ""
        $("#main_shower").append(value + result)
        $(".cmd_input").remove()

        $("#main_shower").append(get_cmd_input())

        var max_len = $("#main_shower").width()

        width = 0.95 * (max_len - $(".cmd_input").offset().left)
        if (width < 100){
            width = 0.95 * max_len 
        }
        $(".cmd_input").css("width", parseInt(width)+ "px")
    }else{
        if(is_tab){
            var split = result.lastIndexOf("\r\n")
            if(split == -1){
                $cmd.val($cmd.val() + result)
            }else{
                var origin_val = $cmd.val()
                if(result != "\r\n")
                    $(".cmd_input").before(origin_val + "\r\n")
                $(".cmd_input").before(result.substring(0, split))

                var input_val = result.substring(split, result.length)
                $cmd.val(origin_val)

                var split_input = input_val.indexOf(origin_val)
                $(".cmd_input").before(input_val.substring(0, split_input))
            }
        }else{
            $cmd.val($cmd.val() + result)
        }
    }

    var obj = $("#main_shower")[0]
    obj.scrollTop= obj.scrollHeight;
}
function showResult(data) {
    parse_result(data)
}
function showtty(data){
    if(data.status == "FAIL"){
        alert(data.message)
        window.location.reload()
    }else{
        $("header input").attr("disabled","disabled") 
    }
}


function startbtn() {
    $("input[name='startBtn']").click(function () {
        var name = $("#name").val();
        var pwd = $("#password").val();
        var ip = $("#ip").val();
        addr = address + "?name=" + name +"&ip="+ ip+"&password="+pwd;
        open = function () {
            if (typeof(Storage)!=="undefined"){
                myservers.reg(ip, name, pwd)
            }
        }
        close = function () {
            alert("服务器已断开连接");
            location.reload();
        };


        ws = new openWebsocket(addr, open, close);
    })
}

function logout() {
    ws.send($.toJSON({"_mapping":"logout"}));
}
